package com.sjgame.base.controller;

import com.sjgame.base.common.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

/**
 * create by zcl
 */
@Controller
public class MsgController extends BaseController {
    @javax.annotation.Resource(name = "redisStringTemplate")
    private RedisTemplate<String, String> redisTemplate;
    private static String prefix = "phone:code:";

//    @Autowired
//    private RedisUtils redisUtils;

    @RequestMapping(value = {"/", "/sendMsgCode"} ,method = RequestMethod.POST)
    @ResponseBody
    public JsonResult sendMsgCode(String phoneNumber, ModelMap map) {
        try {
           // redisUtils.set("1589565","4545",1800L,TimeUnit.SECONDS);
            String code = ((int)(Math.random()*9+1)*1000)+"";
            redisTemplate.opsForValue().set(prefix +phoneNumber ,code);
            redisTemplate.expire(prefix +phoneNumber , 120, TimeUnit.SECONDS);

        } catch (Exception e) {
            return JsonResult.failure("后台短信发送失败");
        }
        return JsonResult.success();

    }


    @RequestMapping(value = {"/", "/checkMsgCode"})
    @ResponseBody
    public JsonResult checkMsgCode(ModelMap map, String msgNum, String phoneNumber) {
        try {
           String code = redisTemplate.opsForValue().get(prefix +phoneNumber);
           if(!StringUtils.equals(msgNum,code)){
               return JsonResult.failure("短信验证码不正确");
           }
        } catch (Exception e) {
            return JsonResult.failure("短信验证码不正确");
        }
        return JsonResult.success();

    }

    public static void main(String[] args) {
        System.out.println((int)((Math.random()*9+1)*1000));
    }
}
